package com.gko.util;

import java.util.List;

public class StringUtil {

	/**
	 * Checks whether string 2 is the prefix of the string 1. All the characters
	 * that match the ignore regex are ignored.
	 * 
	 * @param param
	 * @param prefix
	 * @param ignoreRegex
	 * @param ignoreCase 
	 * @author gheorghi.kozlovskii
	 * */
	public static boolean startsWith(String param, String prefix,
			String ignoreRegex, boolean ignoreCase) {

		// The prefix cannot be shorter than the actual string
		if (prefix.length() > param.length()) {
			return false;
		}

		// Excluding the illegal characters from the parameters
		String filteredParam = param.replaceAll(ignoreRegex, "");
		String filteredPrefix = prefix.replaceAll(ignoreRegex, "");
		
		if (ignoreCase) {
			return filteredParam.toLowerCase().startsWith(filteredPrefix.toLowerCase()); 
		} else {
			return filteredParam.startsWith(filteredPrefix);
		}
	}
	
	public static boolean startsWithIgnoreCase(String param, String prefix,
			String ignoreRegex) {
		return startsWith(param, prefix, ignoreRegex, true);
	}

	/**
	 * @return Returns either the passed in String, or if the String is null, an empty String ("").
	 * @author gheorghi.kozlovskii
	 * */
	public static String defaultString(String param) {
		return param == null ? "" : param;
	}

	/**
	 * Finds the shortest string in the list.
	 * 
	 * @param param The list that is going to be processed
	 * @return The length
	 * @author gheorghi.kozlovskii
	 * */
	public static int findMinLength(List<String> param) {
	
		int minLen = param.get(0).length();
	
		for (String phrase : param) {
			if (minLen > phrase.length()) {
				minLen = phrase.length();
			}
		}
	
		return minLen;
	}

	/**
	 * Iterates through the list of strings and checks whether at the given position (index) the character is a letter.
	 * 
	 * @param index The position of the letter
	 * @param phrases The list of strings that is going to be processed
	 * 
	 * @author gheorghi.kozlovskii
	 * */
	public static boolean hasAtLeastOneLetterAt(int index, List<String> phrases) {
	
		boolean result = false;
	
		for (String phrase : phrases) {
			try {
				char ch = phrase.charAt(index);
				if (!Character.isDigit(ch)) {
					result = true;
					break;
				}
			} catch (StringIndexOutOfBoundsException e) {
				throw new StringIndexOutOfBoundsException(
						"An error occured while processing the string \""
								+ phrase + "\" at the index: " + index);
			}
		}
	
		return result;
	}
}
